var express = require('express');
var router = express.Router();
var Manager = require('../modules/mongo')
var DBManager =new Manager()

//新增班级
router.post('/newClass',function(req, res, next){
    let req_data = req.body
    let query ={
        bjName: req_data.bjName,
        gradeName: req_data.gradeName
    }
    let params ={
        bjName: req_data.bjName,
        gradeName: req_data.gradeName,
        create_time: new Date(),
        update_time: new Date()
    }
    DBManager.findOne('bj', query, result => {
        if(result.success){
            res.send({success:true, code:0,message:'班级已经存在',data:result.result})
            return 
        }
        DBManager.insert('bj', params, result =>{
            if(result.success){
                res.send({success:true, code:0,message:'新增班级成功'})
            }else{
                res.send({success:false,code:1,message:'新增班级失败'});
            }
        })
    })
})

//查询所有班级
router.get('/', function(req, res, next){
    let req_data =req.query
    let params = {
        bjName: {$regex: req_data.bjName, $options: 'i' },
        gradeName: {$regex: req_data.gradeName, $options: 'i' }
    }
    DBManager.find('bj', params, {}, function(result){
        if(result.success){
            res.send({success:true, code:0,message:'查询用户成功',data:result.result})
        }else{
            res.send({success:false,code:1,message:'查询失败',data:[]});
        }
    })
})

//移除班级
router.post('/deletebj', function(req, res, next){
    let  req_data = req.body
    DBManager.delete('bj', req_data).then(result => {
        if(result.success){
            res.send({success:true, code: 0, message:'删除班级成功'})  
            return 
        }
        res.send({success:false, code: 1, message:'删除班级失败'}) 
    }).catch(err => {
        res.send({success: false, result: err, message:'删除班级失败'}) 
    })
})

//修改班级
router.post('/updatebj', function(req, res, next){
    let req_data = req.body
    let params = {
        bjName: req_data.bjName,
        gradeName: req_data.gradeName,
        update_time: new Date()
    }
    DBManager.update('bj', {_id: req_data._id}, {$set: params}).then(result => {
        if(result.success){
            res.send({success:true ,code:0, message:'更新完成'})
            return 
        }
        res.send({success: false, result: 1, message:'更新失败'}) 
    }).catch(err => {
        res.send({success: false, result: err, message:'更新失败'}) 
    })
})
module.exports = router;